# -*- coding: utf-8 -*-

import os

from PIL import Image
from PyPDF2 import PdfFileReader
from reportlab.lib.pagesizes import portrait
from reportlab.pdfgen import canvas
from com.maycur.oss.common.basic_operation import OssOperation


class FixPdfFile:
    fix_pdf_format_backup = '__fix_pdf_format_backup'

    oss_operation: OssOperation

    def __init__(self):
        self.oss_operation = OssOperation()

    @staticmethod
    def is_valid_pdf_file(pdf_path: str):
        """
        判断PDF文件是否损坏，参考文档：https://blog.csdn.net/qq_43309133/article/details/108237233
        """
        valid = True
        try:
            reader = PdfFileReader(pdf_path)
            if reader.getNumPages() < 1:
                valid = False
        except UnicodeDecodeError as e:
            valid = False
        return valid

    @staticmethod
    def convert_image_to_pdf(image_path: str, pdf_path: str):
        """
        将图片转换为PDF，参考文档：https://blog.csdn.net/qq_45689158/article/details/121181946
        """
        (w, h) = Image.open(image_path).size
        pdf = canvas.Canvas(pdf_path, pagesize=portrait((w, h)))
        pdf.drawImage(image_path, 0, 0, w, h)
        pdf.setPageSize((w, h))
        pdf.showPage()
        pdf.save()

    def fix_damage_pdf(self, resource_key: str):
        # 先将PDF文件下载到本地临时文件
        temp_pdf_file = f'/var/tmp/{resource_key.replace("/", "-")}'
        temp_jpg_file = ''
        try:
            self.oss_operation.download(resource_key, temp_pdf_file)
            is_valid_pdf = self.is_valid_pdf_file(temp_pdf_file)
            if is_valid_pdf:
                print(f'resource key: {resource_key} is already valid pdf file, no need to process')
                return
            # PDF文件已损坏，有可能是修复DB-30265时引入的，先将临时文件的pdf文件后缀名改为.jpg
            file_parts = os.path.splitext(temp_pdf_file)
            if file_parts[1].lower() == '.pdf':
                temp_jpg_file = file_parts[0] + '.jpg'
                os.rename(temp_pdf_file, temp_jpg_file)

                # 图片格式转换为PDF
                self.convert_image_to_pdf(temp_jpg_file, temp_pdf_file)
                print(f'resource key: {resource_key} convert format  from .jpg to .pdf, completed')

                # 备份原始PDF文件
                self.oss_operation.backup_resource(resource_key, suffix=self.fix_pdf_format_backup)
                print(f'resource key: {resource_key} backup origin file, completed')

                # 重新上传，覆盖resource_key
                self.oss_operation.upload_file(resource_key, temp_pdf_file)
                print(f'resource key: {resource_key} upload to override origin file, completed')
        except Exception as e:
            raise e
        finally:
            # 清理临时文件
            if os.path.exists(temp_pdf_file):
                os.remove(temp_pdf_file)
            if os.path.exists(temp_jpg_file):
                os.remove(temp_jpg_file)


if __name__ == '__main__':
    fix_pdf_file = FixPdfFile()
    fix_pdf_file.fix_damage_pdf('EC2009081WMNFGG4/16509124-731a-480b-9eb5-23fa0a827fab.pdf')
